package cc.catface.common.aspect;

import com.alibaba.fastjson2.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Enumeration;

@Aspect
@Component
//@Profile({"dev", "test"})
public class NetLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(NetLogAspect.class);
    private static final String LINE_SEPARATOR = System.lineSeparator();//换行符

    @Pointcut("@annotation(cc.catface.common.aspect.NetLog)")
    public void netLog() {
    }

    @Before("netLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return;
        HttpServletRequest request = attributes.getRequest();
        //注解的desc(现value)描述信息
        String desc = getAspectLogDescription(joinPoint);
        //注解的skip描述信息
        boolean skip = getAspectLogSkip(joinPoint);
        //请求头
        StringBuilder reqHeader = new StringBuilder();
        Enumeration<String> reqHeadNames = request.getHeaderNames();
        while (reqHeadNames.hasMoreElements()) {
            String reqHeadName = reqHeadNames.nextElement();
            reqHeader.append(reqHeadName).append(":").append(request.getHeader(reqHeadName)).append(", ");
        }
        //get参数
        String queryString = (request.getQueryString() == null) ? "" : URLDecoder.decode(request.getQueryString());
        logger.info("========================================== ↓Start↓ ==========================================");
        logger.info("METHOD & URL & IP     : {} {} {}", request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr());
        logger.info("DESC & CLASS.METHOD   : {} {}.{}", desc, joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        logger.info("REQ-HEADER            : {}", reqHeader);
        logger.info("REQ-PARAMS(QUERY)     : {}", queryString);
        if (!skip) logger.info("REQ-PARAMS(BODY)      : {}", JSON.toJSON(joinPoint.getArgs()));//返回[]
        logger.info("REQ-SESSION-ID        : {}", request.getSession().getId());

        HttpServletResponse response = attributes.getResponse();
        if (response == null) return;
        //响应头
        StringBuilder resHeader = new StringBuilder();
        Collection<String> resHeadNames = response.getHeaderNames();
        resHeadNames.forEach(header -> resHeader.append(header).append(":").append(response.getHeader(header)).append(", "));
        logger.info("RES-CODE              : {}", response.getStatus());
        logger.info("RES-HEADER            : {}", resHeader);
    }


    @Around("netLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        logger.info("RES                   : {}", JSON.toJSON(result));
        logger.info("TIME-CONSUMING        : {}ms", System.currentTimeMillis() - startTime);
        logger.info("=========================================== ↑End↑ ===========================================" + LINE_SEPARATOR);
        return result;
    }

    @After("netLog()")
    public void doAfter() throws Throwable {
    }

    /* 获取切面注解的desc(现value)描述 */
    public String getAspectLogDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clz = method.getParameterTypes();
                if (clz.length == arguments.length) {
                    description.append(method.getAnnotation(NetLog.class).value());
                    break;
                }
            }
        }
        return description.toString();
    }

    /* 获取切面注解的skip描述 */
    public Boolean getAspectLogSkip(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        Boolean description = false;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clz = method.getParameterTypes();
                if (clz.length == arguments.length) {
                    description = (method.getAnnotation(NetLog.class).skip());
                    break;
                }
            }
        }
        return description;
    }
}
